"""用户、角色管理器"""

import jwt
from src.core import log
from flask import request
from src.db import dbm, dbs
from datetime import datetime
from src.api.origin import blacklist
from src.utils.deep import get_os_info
from src.core.variables.status import *
from src.core.variables.function import *
from src.core.variables.exception import *
from src.schema.core_user import login_schema
from flask_jwt_extended import verify_jwt_in_request, get_jwt
from jwt.exceptions import InvalidTokenError, ExpiredSignatureError
from flask_jwt_extended import create_access_token, create_refresh_token


def signup(schema):
    """注册用户"""
    now = get_os_info().local_time("no week")
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_session.add(
            dbs.sys_default.User(
                uid=CREATE_ID(),
                username=schema.username,
                password=ENCRYPTION(schema.password),
                email=schema.email,
                phone=schema.phone,
                roles=str(schema.roles),
                create_time=now,
                update_time=now,
                last_login_time=now,
                last_login_ip=request.remote_addr,
                login_count="0",
            )
        )
        if dbm.commit(db_session):
            return SUCCESS_CODE.SIGNUP_SUCCESS()
        raise MAIN_EXCEPTION(f"提交数据库更改失败！")


def login(schema: login_schema):
    """登录"""
    if not schema.username or not schema.password:
        return ERROR_CODE.INVALID_JSON()
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.sys_default.User)
            .filter(dbm.and_(dbs.sys_default.User.username == schema.username))
            .first()
        )
        if db_result:
            if (
                schema.username == db_result.username
                and schema.password == db_result.password
            ):
                db_result.last_login_time = get_os_info().local_time("no week")
                db_result.last_login_ip = request.remote_addr
                db_result.login_count = str(int(db_result.login_count) + 1)
                if dbm.commit(db_session):
                    return SUCCESS_CODE.LOGIN_SUCCESS(
                        {
                            "access_token": create_access_token(
                                schema.username,
                                additional_claims={"roles": [db_result.roles]},
                            ),
                            "refresh_token": create_refresh_token(
                                schema.username,
                                additional_claims={"roles": [db_result.roles]},
                            ),
                            "uid": db_result.uid,
                        }
                    )
            return ERROR_CODE.USERNAME_PASSWORD_INCORRECT()
        return ERROR_CODE.USER_NOT_FOUND()


def remove_user(schema):
    """删除用户"""
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        if schema.username in ["admin"]:
            result = "用户 [{}] 为系统用户，禁止删除！".format(schema.username)
        elif (
            not db_session.query(dbs.sys_default.User)
            .filter(dbs.sys_default.User.username == schema.username)
            .first()
        ):
            result = "用户 [{}] 不存在！".format(schema.username)
        else:
            # TODO 删除前校验是否存在内容绑定
            # 不存在内容绑定时
            db_session.delete(
                db_session.query(dbs.sys_default.User)
                .filter(dbs.sys_default.User.username == schema.username)
                .first()
            )
            if dbm.commit(db_session):
                return SUCCESS_CODE_CUSTOMIZE(
                    "用户 [{}] 删除成功！".format(schema.username), 200
                )
        return ERROR_CODE_CUSTOMIZE(result, 400)


def refresh_token(current_user, jwt_data):
    """刷新token"""
    jti = jwt_data.get("jti")
    blacklist.add(jti)
    new_access_token = create_access_token(
        identity=current_user,
        additional_claims={
            "role": jwt_data.get("role", "user"),
            "fresh": False,  # 标记为不是新鲜token
        },
    )
    new_refresh_token = create_refresh_token(
        identity=current_user,
        additional_claims={
            "role": jwt_data.get("role", "user"),
            "fresh": False,  # 标记为不是新鲜token
        },
    )
    remaining_time = datetime.fromtimestamp(jwt_data["exp"]) - datetime.utcnow()
    log.INFO(
        f"用户 {current_user} 刷新了access token (原刷新token剩余有效期: {str(remaining_time)})"
    )
    return SUCCESS_CODE_CUSTOMIZE(
        {
            "access_token": new_access_token,
            # "refresh_token": new_refresh_token
        },
        200,
    )


def update_user(schema):
    """更新用户"""
    ...
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.sys_default.User)
            .filter(dbs.sys_default.User.uid == schema.uid)
            .first()
        )
        if db_result:
            db_result.update(
                {
                    "email": schema.email,
                    "phone": schema.phone,
                    "roles": str(schema.roles),
                    "update_time": get_os_info().local_time("no week"),
                }
            )
        if dbm.commit(db_session):
            return SUCCESS_CODE.UPDATE_SUCCESS()
        return ERROR_CODE.UPDATE_FAILED()


def update_passwd(schema):
    """更新密码"""
    with dbm.get("sys_default") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.sys_default.User)
            .filter(dbs.sys_default.User.uid == schema.uid)
            .first()
        )
        if db_result:
            db_result.update(
                {
                    "password": ENCRYPTION(schema.password),
                    "update_time": get_os_info().loFcal_time("no week"),
                }
            )
        if dbm.commit(db_session):
            return SUCCESS_CODE.UPDATE_SUCCESS()
        return ERROR_CODE.UPDATE_FAILED()


# def check_token(token, app):
#     """校验token"""
#     try:
#         verify_jwt_in_request()
#         token_data = get_jwt()
#         if token_data["type"] != "access":
#             return {"valid": False, "error": "非 Access Token"}
#         return {
#             "valid": True,
#             "user_identity": token_data["sub"],  # 用户标识
#             "payload": token_data
#         }
#     except Exception as e:
#         return {"valid": False, "error": str(e)}

#     try:
#         verify_jwt_refresh_token_in_request()
#         token_data = get_jwt()
#         if token_data["type"] != "refresh":
#             return {"valid": False, "error": "非 Refresh Token"}
#         return {
#             "valid": True,
#             "user_identity": token_data["sub"],  # 用户标识
#             "payload": token_data
#         }
#     except Exception as e:
#         return {"valid": False, "error": str(e)}
